<template>
  <basic-container>
    <div class="navgatior">
      <a href="#one">基本信息</a>
      <a href="#two">自然属性</a>
      <a href="#three">销售属性</a>
      <a href="#four">物流信息</a>
      <a href="#five">详情描述</a>
      <a href="#six">其他信息</a>
    </div>
    <div>
      <h3 id="one">基本信息</h3>
      <div class="fromRow">
        <span>商品分类：</span>
        <el-cascader v-model="productData"
                     :options="chooseProductOption"
                     size="mini"
                     @change="handleChange">
        </el-cascader>
      </div>
      <div class="fromRow">
        <span>商品名称：</span>
        <el-input type="textarea"
                  maxlength="50"
                  show-word-limit
                  v-model="AddGoodsFinishParam.goods.goodsName"
                  placeholder="商品标题名称长度至少1个字符，最长50个汉字"
                  :rows="1"></el-input>
      </div>
      <div class="fromRow">
        <span>商品品牌：</span>
        <el-select v-model="AddGoodsFinishParam.goods.goodsBrandId"
                   size="mini"
                   placeholder="请选择">
          <el-option v-for="item in brandData"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="fromRow">
        <span>商品类型：</span>
        <el-radio v-model="AddGoodsFinishParam.goods.choiceType"
                  label="0">实物商品</el-radio>
        <el-radio v-model="AddGoodsFinishParam.goods.choiceType"
                  label="1">虚拟商品</el-radio>
        <div class="msg">充值卡、消费券等属于虚拟商品</div>
      </div>
      <div class="fromRow">
        <span>商品图片：</span>
        <up-load-img ref="upimg"></up-load-img>
      </div>
    </div>
    <el-divider></el-divider>
    <div>
      <h3 id="two">商品自然属性</h3>
      <div class="fromRow">
        <span v-for="(ele,index) in spec"
              :key="index">
          <span>{{ele.specName}}：</span>
          <el-select v-model="brand[index]"
                     size="mini"
                     placeholder="请选择">
            <el-option v-for="item in ele.childrenNodes"
                       :key="item.id"
                       :label="item.specpValue"
                       :value="item.id">
            </el-option>
          </el-select>
        </span>
      </div>
    </div>
    <el-divider></el-divider>
    <div>
      <h3 id="three">商品销售属性</h3>
      <div class="fromRow">
        <span>库存配置：</span>
        <el-radio v-model="AddGoodsFinishParam.goods.inventoryType"
                  label="all">全局配置</el-radio>
        <el-radio v-model="AddGoodsFinishParam.goods.inventoryType"
                  label="spec">规格配置</el-radio>
        <p class="msg">全局配置表示所有规格无单独库存、价格配置
          规格配置需要配置对应属性的库存、价格</p>
      </div>
      <div class="globalConfig"
           v-if="AddGoodsFinishParam.goods.inventoryType === 'all'">
        <div class="fromRow">
          <span>商品编号：</span>
          <el-input style="width:180px;margin-right:40px;"
                    size="mini"
                    v-model="AddGoodsFinishParam.goodsSerial"></el-input>
          <p class="msg">
            商品编号是指卖家个人管理商品的编号，买家不可见
            最多可输入50个字符，支持输入中文、字母、数字、_、/、-和小数点</p>
        </div>
        <div class="fromRow">
          <span>商品库存：</span>
          <el-input style="width:180px;margin-right:40px;"
                    size="mini"
                    v-model="AddGoodsFinishParam.goodsInventory"></el-input>
          <p class="msg">
            商品库存数量只能是0-1000000之间的整数
          </p>
        </div>
        <div class="fromRow">
          <span>价格：</span>
          <el-input class="price"
                    v-model="AddGoodsFinishParam.price"
                    size="mini"
                    placeholder="请输入价格"></el-input>
          <div class="msg">价格必须是0.01-99999999.99之间的数字</div>
        </div>
        <div class="fromRow">
          <span>商品原价：</span>
          <el-input class="price"
                    v-model="AddGoodsFinishParam.originalPrice"
                    size="mini"
                    placeholder="请输入价格"></el-input>
          <div class="msg">价格必须是0.01-99999999.99之间的数字</div>
        </div>
        <div class="fromRow">
          <span>进货价：</span>
          <el-input class="price"
                    v-model="AddGoodsFinishParam.purchasePrice"
                    size="mini"
                    placeholder="请输入价格"></el-input>
          <div class="msg">价格必须是0.01-99999999.99之间的数字</div>
        </div>
      </div>

      <div class="specConfig"
           v-if="AddGoodsFinishParam.goods.inventoryType === 'spec'">
        <div class="fromRow"
             v-for="item in saleSpec"
             :key="item.id">
          <check-item :checkdata="item.childrenNodes"
                      :specName="item.specName"
                      :specModule="item.specModule"
                      :specId="item.id"
                      :item="item"
                      @receptionSpec="recSpec"></check-item>
        </div>
        <div class="fromRow">
          <span style="width: 160px;">详细库存：</span>
          <table>
            <tr>
              <td>规格</td>
              <td>库存</td>
              <td>价格</td>
              <td>商品原价</td>
              <td>进货价</td>
              <td>商品编码</td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td>
                <el-input size="mini"
                          style="width:80px"
                          v-model="prospec.goodsInventory"></el-input>
              </td>
              <td>
                <el-input size="mini"
                          style="width:80px"
                          v-model="prospec.price"></el-input>
              </td>
              <td>
                <el-input size="mini"
                          style="width:80px"
                          v-model="prospec.originalPrice"></el-input>
              </td>
              <td>
                <el-input size="mini"
                          style="width:80px"
                          v-model="prospec.purchasePrice"></el-input>
              </td>
              <td>
                <el-input size="mini"
                          style="width:80px"
                          v-model="prospec.goodsSerial"></el-input>
              </td>
              <td>
                <el-button type="primary"
                           size="mini"
                           @click="confirmFill">确认填充</el-button>
              </td>
            </tr>

            <tr v-for="(item,index) in tabledata"
                :key="index">
              <td>{{item.value}}</td>
              <td>
                <el-input size="mini"
                          style="width:80px"
                          v-model="item.goodsInventory"></el-input>
              </td>
              <td>
                <el-input size="mini"
                          style="width:80px"
                          v-model="item.price"></el-input>
              </td>
              <td>
                <el-input size="mini"
                          style="width:80px"
                          v-model="item.originalPrice"></el-input>
              </td>
              <td>
                <el-input size="mini"
                          style="width:80px"
                          v-model="item.purchasePrice"></el-input>
              </td>
              <td>
                <el-input size="mini"
                          style="width:80px"
                          v-model="item.goodsSerial"></el-input>
              </td>
            </tr>
          </table>
        </div>
      </div>
    </div>
    <el-divider></el-divider>
    <div>
      <h3>店铺分类</h3>
      <div class="fromRow">
        <span>本店分类：</span>
        <el-button style="margin-right:20px;height: 28px;line-height: 14px;padding: 0 15px;"
                   type="primary"
                   size="mini"
                   @click="goodsClassOpen">新增分类</el-button>
        <el-select v-model="AddGoodsFinishParam.goods.userGoodsClassId"
                   style="margin-right:20px;"
                   size="mini"
                   placeholder="请选择">
          <el-option v-for="(item,index) in storeClassData"
                     :key="index"
                     :label="item.className"
                     :value="item.id"
                     :disabled="item.deleteStatus">
          </el-option>
        </el-select>
        <p class="msg">商品可以从属于店铺的多个分类之下,店铺分类可以由 "卖家中心 -> 商品管理 ->商品分类" 中自定义</p>
      </div>
    </div>
    <el-divider></el-divider>
    <div>
      <h3 id="four">物流信息</h3>
      <div class="fromRow">
        <el-radio-group v-model="isSelfSupply">
          <el-radio :label="0">自供货</el-radio>
          <el-radio :label="1">供货商</el-radio>
        </el-radio-group>
      </div>
      <div class="fromRow" v-if="isSelfSupply == 1">
        <span>供货商：</span>
        <el-select v-model="AddGoodsFinishParam.goods.supplierId"
                   size="mini"
                   placeholder="请选择">
          <el-option v-for="(item,index) in supplierdata"
                     :key="index"
                     :label="item.title"
                     :value="item.id">
          </el-option>
        </el-select>
      </div>
      <div class="fromRow">
        <span>运费模板：</span>
        <el-select v-model="AddGoodsFinishParam.goods.transportId"
                   size="mini"
                   placeholder="请选择">
          <el-option v-for="(item,index) in templateFreightData"
                     :key="index"
                     :label="item.transName"
                     :value="item.id">
          </el-option>
        </el-select>
        <el-button style="margin-left:20px"
                   type="primary"
                   @click="templateFreightHandle"
                   size="mini">添加运费模板</el-button>
      </div>
      <div class="fromRow">
        <span>商品属性：</span>
        <div>
          <el-card class="box-card">
            <div class="fromRow">
              <span>长度：</span>
              <el-input style="width:80px;margin-right:10px;"
                        size="mini"
                        v-model="AddGoodsFinishParam.goodsLength"></el-input>
              <span>cm</span>
            </div>
            <div class="fromRow">
              <span>宽度：</span>
              <el-input style="width:80px;margin-right:10px;"
                        size="mini"
                        v-model="AddGoodsFinishParam.goodsWidth"></el-input>
              <span>cm</span>
            </div>
            <div class="fromRow">
              <span>高度：</span>
              <el-input style="width:80px;margin-right:10px;"
                        size="mini"
                        v-model="AddGoodsFinishParam.goodsHeight"></el-input>
              <span>cm</span>
            </div>
            <div class="fromRow">
              <span>体积：</span>
              <el-input style="width:80px;margin-right:10px;"
                        size="mini"
                        v-model="goodsVolume"></el-input>
              <span>m³</span>
            </div>
            <div class="fromRow">
              <span>重量：</span>
              <el-input style="width:80px;margin-right:10px;"
                        size="mini"
                        v-model="AddGoodsFinishParam.goodsVolumeWeight"></el-input>
              <span>kg</span>
            </div>
          </el-card>
        </div>
      </div>
    </div>
    <el-divider></el-divider>
    <div>
      <h3 id="five">详情描述</h3>
      <div class="fromRow">
        <span style="width: 160px;" >PC商品描述：</span>
        <editor @getContent="getEditcont"></editor>
      </div>
      <div class="fromRow">
        <span style="width: 160px;" >H5商品描述：</span>
        <editor @getContent="getEditconth5"></editor>
      </div>
    </div>
    <el-divider></el-divider>
    <div>
      <h3 id="six">其他信息</h3>
      <div class="fromRow">
        <span>商品推荐：</span>
        <el-radio v-model="AddGoodsFinishParam.goods.goodsRecommend"
                  label="1">是</el-radio>
        <el-radio v-model="AddGoodsFinishParam.goods.goodsRecommend"
                  label="0">否</el-radio>
        <p class="msg">被推荐的商品会显示在店铺首页</p>
      </div>
      <div class="fromRow">
        <span>商品权重：</span>
        <el-input style="width:180px"
                  size="mini"
                  v-model="AddGoodsFinishParam.goods.goodsSort"></el-input>
        <p class="msg">权重越小越靠前，最大不超过999</p>
      </div>
      <div class="fromRow">
        <el-button size="mini"
                   type="primary"
                   @click="submit">提交审核</el-button>
      </div>
    </div>
    <template-freight ref="templatefre"></template-freight>
    <el-dialog title="新增分类" :visible.sync="dialogTableVisible" width="80%">
      <goods-class v-if="dialogTableVisible" :goodsid="goodsId"></goods-class>
    </el-dialog>
  </basic-container>
</template>
<script>
// getProductdata   调用方法
import { getList, getGoodsBrand, loadClassSpec, getStoreCate, getsupplierlist, gettemplateFre, submitdata,getProductdata } from '@/api/base/goods/addGoods'
import checkItem from '@/components/goods/seller/checkItem'
import upLoadImg from '@/components/goods/uploadimg'
import editor from '@/components/editor/richTextEditor'
import templateFreight from '@/components/goods/seller/templateFreight'
import goodsClass from '@/views/base/goods/seller/goodsClass';
export default {
  props:{
    goodsid:{
      type:String,
      default:'',
    },
  },
  data () {
    return {
      dialogTableVisible:false,
      storeId:'',
      AddGoodsFinishParam: {
        goods: {
          goodsName: '',
          goodsClassId: '',
          goodsBrandId: '',
          choiceType: '0',
          goodsMainPhotoUrl: '',
          goodsInventory: '',//商品库存
          supplierId: '',//供货商
          transportId: '',//运费模板
          goodsRecommend: '1',//商品推荐
          goodsSort: '',//权重
          inventoryType: 'all',//配置(全局/规格)
          userGoodsClassId: '',//店铺分类
        },
        goodsPhotos: '',
        goodsSerial: '', //商品编号
        purchasePrice: '',//进货价
        originalPrice: '',//原价
        goodsLength: '',//长
        goodsWidth: '',//宽
        goodsHeight: '',//高
        goodsVolume: '',//体积
        goodsVolumeWeight: '',//重量
        goodsDetails: '',//商品详情
        goodsDetailsH5: '',//商品详情H5
        intentoryDetails: '',//规格配置
        goodsPropertyIds: [],
      },
      prospec: {
        goodsInventory: '',//填充库存
        price: '',//填充售卖价格
        originalPrice: '',//填充商品原价
        purchasePrice: '',//填充商品进货价
        goodsSerial: '',//填充商品编码
      },
      isSelfSupply: 0,
      isFill: false,//是否填充规格
      spec: [], //自然属性
      saleSpec: [],//销售属性
      productData: [],
      productLastdata: '',
      chooseProductOption: [],
      brandData: [],
      supplier: '',//运费模板
      brand: [],
      specification: '1',//库存配置
      storeClassData: [],//本店分类列表数据
      supplierdata: [],//供货商数据列表
      templateFreight: '',//运费模板数据
      templateFreightData: [],//运费模板数据列表
      dataArr: [],
      tabledata: [],
      choosedata: [],
      allExceptSpecList:[],
    }
  },
  components: {
    upLoadImg,
    editor,
    templateFreight,
    checkItem,
    goodsClass
  },
  computed:{
    goodsVolume(){//计算体积
      let tj = this.AddGoodsFinishParam["goodsLength"] * this.AddGoodsFinishParam["goodsWidth"] * this.AddGoodsFinishParam["goodsHeight"]
      this.AddGoodsFinishParam.goodsVolume = tj;
      return tj;
    }
  },
  watch: {
    'isSelfSupply' (val) {
      if (val == 0) {
        //自供货
        this.gettemplateFre()
      }else{
        this.templateFreightData=[]
      }
    },
    'AddGoodsFinishParam.goods.supplierId' (val) {
      this.gettemplateFre(val)
    },
    'chooseProductOption'(val){
      console.log(val)
    }
  },
  created () {
    getList().then(res => {
      if (res.data.code == 200) {
        this.chooseProductOption = res.data.data
      }
    })
    // this.getProductdata();
  },
  methods: {
    //新增分类
    goodsClassOpen(){
        this.dialogTableVisible=true;
        return false
    },

    getProductdata(){
      getProductdata(this.goodsid).then(res => {
        if (res.data.code == 200) {
          let allspec = res.data.data.allSpecInfo
          this.AddGoodsFinishParam.goods.inventoryType = 'spec'
          let showdata = res.data.data.showData
          this.tabledata = showdata.skuTableInfo.map(item => {
            if(item.value){
              item.value = item.value.join(',')
            }
            return item
          })

          this.saleSpec = allspec.map(item => {
            item.choosedata = showdata.gsptyInfoList
            return item
          })

          this.allExceptSpecList  = showdata.allExceptSpecList
          this.productData.push(this.allExceptSpecList[0].goodsClassOutId)
          this.productData.push(this.allExceptSpecList[0].goodsClassInChildId)
          this.productData.push(this.allExceptSpecList[0].goodsClassInnerChildId)

          this.handleChange(this.allExceptSpecList[0].goodsClassInnerChildId)

          this.AddGoodsFinishParam.goods.transportId = this.allExceptSpecList[2].transportId
          this.AddGoodsFinishParam.goods.supplierId = this.allExceptSpecList[3].supplierId

        }else{
          return false
        }
      })
    },

    confirmFill () {
      //确认填充商t品库存价格等信息
      // let flag = false
      // for (let i in this.prospec) {
      //   if (this.prospec[i] == '') {
      //     this.$message({
      //       type: 'warning',
      //       message: '规格不能为空！'
      //     })
      //     return
      //   } else {
      //     flag = true
      //   }
      // }
      // if (flag) {
      //   this.$message({
      //     type: 'success',
      //     message: '填充成功！'
      //   })
      //   this.isFill = true;
      // }
      //已经有的也要填充上
      if(this.tabledata.length == 0){
          this.$message({
            type: 'warning',
            message: '没有可以被填充的规格！'
          })
          return;
      }
      this.tabledata.forEach(item => {
          for (let prop in item) {
              if (prop == 'value' || prop == 'ids') {
                  continue
              } else {
                  item[prop] = this.prospec[prop]
              }
          }
      })
      this.$message({
        type: 'success',
        message: '填充成功！'
      })
    },
    //获取商品详情数据
    getEditcont (val) {
      this.AddGoodsFinishParam.goodsDetails = val;
    },
    //获取商品详情数据
    getEditconth5 (val) {
      this.AddGoodsFinishParam.goodsDetailsH5 = val
    },
    submit () {
      this.AddGoodsFinishParam.goodsPhotos = this.$refs.upimg.url.splice(1).join(',')
      this.AddGoodsFinishParam.goods.goodsMainPhotoUrl = this.$refs.upimg.url.splice(0, 1)
      this.AddGoodsFinishParam.intentoryDetails = this.tabledata
      this.AddGoodsFinishParam.goodsClassSpecIds = this.dataArr
      this.AddGoodsFinishParam.intentoryDetails = this.tabledata
      this.AddGoodsFinishParam.goods.goodsClassId = this.productLastdata
      this.AddGoodsFinishParam.goodsPropertyIds = this.brand
      console.log(this.AddGoodsFinishParam);
      submitdata(this.AddGoodsFinishParam).then(res => {
        if (res.data.code == 200) {
          this.$message.success("发布成功！");
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    addUpdate (form, index, done, loading) {
      this.$message.success('模拟网络请求')
      setTimeout(() => {
        this.$message.success('关闭按钮等待')
        loading()
      }, 1000)
      setTimeout(() => {
        this.$message.success(
          '编辑数据' + JSON.stringify(form) + '数据序号' + index
        )
        done()
      }, 2000)
    },
    templateFreightHandle () { //添加运费模板触发弹窗方法
      this.$refs.templatefre.open()
    },
    handleChange (value) { //选择商品数据  点击触发事件
      if(Array.isArray(value)){
      this.productLastdata = value[value.length - 1]
      }else{
        this.productLastdata = value
      }
      getGoodsBrand(this.productLastdata).then(res => {
        if (res.data.code == 200) {
          let brand = res.data.data
          brand.forEach(item => {
            this.brandData.push(new Object({ value: item.id, label: item.brandName }))
          });
        }
      })
      loadClassSpec(this.productLastdata).then(res => {
        //自然属性1  销售属性0
        let data = res.data.data
        this.spec = data.filter(item => {
          if (item.specType == 1) return item
        })
        this.saleSpec = data.filter(item => {
          if (item.specType == 0) return item
        })

      })
      //加载店铺分类
      getStoreCate().then(res => {
        if (res.data.code == 200) {
          this.storeClassData = res.data.data
        }
      })
      //加载供货商列表
      getsupplierlist(this.storeId).then(res => {
        if (res.data.code == 200) {
          this.supplierdata = res.data.data
        }
      })
      this.gettemplateFre()//加载运费模板
    },
    gettemplateFre (supplierId = '') {
      //加载运费模板列表
      gettemplateFre(supplierId).then(res => {
        if (res.data.code == 200) {
          this.templateFreightData = res.data.data
        }
      })
    },

    arrsort (property) {
      return (a, b) => {
        var val1 = a[property]
        var val2 = b[property]
        return val1 - val2
      }
    },
    generateTable () {
      this.tabledata = [];
      var trData = [];
      this.dataArr.sort(this.arrsort('specId'))
      if (this.dataArr.length > 0) {
        trData = this.generateTable2(trData, "", "", 0);
      }

      if (this.isFill) {
        //已经填充过属性
        console.log(trData)
        trData.forEach(item => {
          for (let prop in item) {
            if (prop == 'value' || prop == 'ids') {
              continue
            } else {
              item[prop] = this.prospec[prop]
            }
          }
        })
        console.log(trData)
        this.tabledata = trData;
      } else {
        this.tabledata = trData;
      }

    },
    generateTable2 (trData, ggName, id, index) {
      if (this.dataArr.length - 1 <= index) {
        this.dataArr[index].specdata.forEach(item => {
          var _ggName;
          var ids;
          if (ggName == "" || id == "") {
            _ggName = item.specpValue;
            ids = item.id
          } else {
            _ggName = ggName + "," + item.specpValue;
            ids = id + "_" + item.id
          }
          var tr = {};
          tr.value = _ggName;
          tr.ids = ids;
          tr.goodsInventory = '';//商品库存
          tr.price = '';//商品售卖价格
          tr.purchasePrice = '',//进货价
            tr.originalPrice = '',//原价
            tr.goodsSerial = '',//商品编号
            trData.push(tr);
        })
        return trData;
      } else {
        this.dataArr[index].specdata.forEach(item => {
          var _ggName;
          var ids;
          if (ggName == "") {
            _ggName = item.specpValue;
            ids = item.id
          } else {
            _ggName = ggName + "," + item.specpValue;
            ids = id + "_" + item.id
          }
          trData = this.generateTable2(trData, _ggName, ids, index + 1);
        })
        return trData;
      }
    },
    recSpec (res) {// 接收规格数据
      if (res.specdata.length == 0) {
        this.dataArr = this.arrayFn.removeObjByKey(this.dataArr, res, "specId")
      } else {
        this.dataArr = this.arrayFn.insertAndUpdateObjByKey(this.dataArr, res, "specId");
      }
      this.generateTable();
    }
  }
}
</script>
<style scoped>
.navgatior {
  width: 70px;
  height: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-flow: column nowrap;
  position: absolute;
  right: 0;
}
.navgatior a {
  text-align: center;
  letter-spacing: 5px;
  padding: 8px 5px;
  background: rgba(173, 173, 173, 0.5);
  border-radius: 4px;
  margin-bottom: 8px;
  border: 1px solid #fff;
  writing-mode: vertical-lr;
  color: #fff;
  font-size: 12px;
}
.navgatior a.active,
.navgatior a:hover {
  color: #F39800;
  background: #ecf5ff;
  border: 1px solid #b3d8ff;
}
.fromRow {
  display: flex;
  justify-content: flex-start;
  width: 80%;
  padding: 10px 0;
}
.el-textarea {
  width: 80%;
}
.msg {
  font-size: 10px;
  color: #999;
}
.price {
  width: 200px;
  margin-right: 20px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 400px;
}
.cardipt {
  width: 200px;
}
.line {
  display: inline;
}
td {
  text-align: center;
}
</style>